package pers.jing.android.helper.page

import androidhelper.composeapp.generated.resources.Res
import androidhelper.composeapp.generated.resources.cancel
import androidhelper.composeapp.generated.resources.ok
import androidhelper.composeapp.generated.resources.start
import androidhelper.composeapp.generated.resources.stop
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Button
import androidx.compose.material.Card
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.LinearProgressIndicator
import androidx.compose.material.MaterialTheme
import androidx.compose.material.OutlinedTextField
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.ArrowDropDown
import androidx.compose.material.icons.rounded.PauseCircle
import androidx.compose.material.icons.rounded.PlayCircle
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.VerticalDivider
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import org.jetbrains.compose.resources.stringResource
import org.koin.compose.viewmodel.koinViewModel
import pers.jing.android.helper.model.DeviceInfo
import pers.jing.android.helper.model.TaskState
import pers.jing.android.helper.model.UITask
import pers.jing.android.helper.widget.SelectDialog
import pers.jing.android.helper.work.DyjsbWork

/**
 * 任务列表页面
 */
@Composable
fun TaskListPage(viewModel: DeviceViewModel = koinViewModel<DeviceViewModel>()) {
    Column(
        modifier = Modifier
            .padding(horizontal = 16.dp, vertical = 10.dp)
    ) {
        var showCreateTaskDialog by remember {
            mutableStateOf(false)
        }
        val taskList = viewModel.taskList.collectAsState()
        Row {
            //创建任务
            Button(
                onClick = {
                    showCreateTaskDialog = true
                },
                modifier = Modifier.weight(1.0f)
            ){
                Text(
                    text = "创建任务"
                )
            }

//            Button(
//                onClick = {
//                    viewModel.startTestTask()
//                },
//                modifier = Modifier.weight(1.0f)
//                    .padding(start = 16.dp)
//            ){
//                Text(
//                    text = "测试任务"
//                )
//            }
        }

        if (showCreateTaskDialog) {
            CreateTaskDialog(
                serialId = viewModel.getCurDeviceSerialId(),
                onDismiss = {
                    showCreateTaskDialog = false
                },
                onOk = { newTask ->
                    showCreateTaskDialog = false
                    viewModel.startTask(uiTask = newTask)
                }
            )
        }
        //任务列表
        LazyColumn(
            modifier = Modifier.fillMaxWidth()
                .padding(top = 10.dp)) {
            items(taskList.value, key = {
                it.id
            }) {
                UITaskWidget(it, onStartTask = {
                    viewModel.startTask(it)
                }, onStopTask = {
                    viewModel.stopTask(it)
                })
            }
        }

    }
}


@Composable
fun CreateTaskDialog(serialId: String, onDismiss: () -> Unit,
                     onOk: (UITask) -> Unit) {
    Dialog(
        onDismissRequest = {
            onDismiss()
        }
    ) {
        Card(
            modifier = Modifier.fillMaxWidth()
        ) {
            val scrollState = rememberScrollState()
            Column(
                modifier = Modifier.fillMaxWidth()
                    .verticalScroll(scrollState),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Text(
                    text = "创建任务",
                    fontSize = 17.sp,
                    fontWeight = FontWeight.Bold,
                    modifier = Modifier.padding(top = 10.dp)
                )

                /**
                 * 时长
                 */
                var duration by remember {
                    mutableStateOf("")
                }

                //间隔
                var interval by remember {
                    mutableStateOf("")
                }

                var okEnabled by  remember {
                    mutableStateOf(false)
                }

                //时长
                OutlinedTextField(
                    value = duration,
                    onValueChange = {
                        duration = it
                        okEnabled = checkOkEnabled(duration, interval)
                    },
                    placeholder = {
                        Text(text = "单位: 分钟, 如60, 表示60分钟之后自动结束")
                    },
                    label = {
                        Text(text = "时长")
                    },
                    //PC上, 设置键盘使用Number, 不生效
                    keyboardOptions = KeyboardOptions(
                        keyboardType = KeyboardType.Number
                    ),
                    modifier = Modifier.fillMaxWidth()
                        .padding(top = 10.dp)
                        .padding(horizontal = 16.dp)
                )
                //间隔
                OutlinedTextField(
                    value = interval,
                    onValueChange = {
                        interval = it
                        okEnabled = checkOkEnabled(duration, interval)
                    },
                    placeholder = {
                        Text(text = "单位: 秒, 如10, 表示每10秒执行一次")
                    },
                    label = {
                        Text(text = "间隔")
                    },
                    keyboardOptions = KeyboardOptions(
                        keyboardType = KeyboardType.Number
                    ),
                    modifier = Modifier.fillMaxWidth()
                        .padding(top = 10.dp)
                        .padding(horizontal = 16.dp)
                )

                HorizontalDivider(
                    modifier = Modifier.fillMaxWidth().padding(top = 10.dp)
                )
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    TextButton(
                        onClick = {
                            onDismiss()
                        },
                        modifier = Modifier.weight(1.0f)
                    ) {
                        Text(
                            text = stringResource(Res.string.cancel),
                            fontSize = 17.sp,
                            color = Color.Black
                        )
                    }

                    VerticalDivider(
                        modifier = Modifier.height(30.dp)
                    )

                    TextButton(
                        onClick = {
                            onOk(UITask(serialId, duration = duration.toIntOrNull()?:60,
                                interval = interval.toIntOrNull()?:10,
                                taskState = TaskState.Init))
                        },
                        modifier = Modifier.weight(1.0f),
                        enabled = okEnabled
                    ) {
                        Text(
                            text = stringResource(Res.string.ok),
                            fontSize = 17.sp
                        )
                    }
                }
            }

        }
    }
}

/**
 * 检查OK按钮是否可以点击
 */
fun checkOkEnabled(duration: String, interval: String): Boolean {
    val tempDuration = duration.toIntOrNull()
    val tempInterval = interval.toIntOrNull()
    if (tempDuration == null || tempInterval == null) {
        return false
    }
    //间隔的单位是秒, 时长的单位是分钟
    if (tempDuration <= 0 || tempInterval < 0 || tempDuration * 60 < tempInterval) {
        return false
    }
    return true
}

@Composable
fun UITaskWidget(uiTask: UITask, onStartTask: (UITask) -> Unit,
                 onStopTask: (UITask) -> Unit) {
    ElevatedCard(
        modifier = Modifier.fillMaxWidth()
    ) {
        Column(
            verticalArrangement = Arrangement.Center,
            modifier = Modifier.fillMaxWidth()
                .padding(horizontal = 16.dp)
                .padding(vertical = 10.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                //任务名称
                Text(
                    text = "任务名称：${uiTask.taskType.name}",
                    style = MaterialTheme.typography.body1
                )
            }

            //任务
            Row(
                modifier = Modifier.fillMaxWidth()
                    .padding(top = 10.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Column(
                    modifier = Modifier.weight(1.0f)
                        .padding(horizontal = 10.dp)
                ) {
                    //执行进度
                    LinearProgressIndicator(
                        progress = uiTask.progress / 100.0f,
                        modifier = Modifier.fillMaxWidth(1.0f),
                        strokeCap = StrokeCap.Round
                    )
                    Row(
                        modifier = Modifier.fillMaxWidth().padding(top = 5.dp),
                        horizontalArrangement = Arrangement.SpaceBetween
                    ) {
                        Text(
                            text = "0"
                        )
                        if (TaskState.Running == uiTask.taskState) {
                            Text(
                                text = "${uiTask.progress}%"
                            )
                        }
                        Text(
                            text = "100"
                        )
                    }
                }

                //执行和暂停按钮
                if (TaskState.Init == uiTask.taskState || TaskState.Completed == uiTask.taskState) {
                    //待执行或已完成, 可以重新启动
                    IconButton(
                        onClick = {
                            onStartTask(uiTask)
                        }
                    ) {
                        Icon(
                            imageVector = Icons.Rounded.PlayCircle,
                            contentDescription = stringResource(Res.string.start)
                        )
                    }
                } else {
                    IconButton(
                        onClick = {
                            onStopTask(uiTask)
                        }
                    ) {
                        Icon(
                            imageVector = Icons.Rounded.PauseCircle,
                            contentDescription = stringResource(Res.string.stop)
                        )
                    }
                }
            }
        }
    }
}